package cn.apotato.server.uaa.config;

import cn.apotato.server.uaa.properties.WebSecurityProperties;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 网络安全配置
 *
 * @author 胡晓鹏
 * @date 2023/05/26
 */
@AllArgsConstructor
@EnableConfigurationProperties(WebSecurityProperties.class)
@EnableWebSecurity
@Configuration
public class WebSecurityConfig{

    private final UserDetailsService userDetailsService;
    private final WebSecurityProperties webSecurityProperties;

    /**
     * 得到白名单
     *
     * @return {@link String[]}
     */
    public String[] getWhiteList() {
        List<String> whiteList = webSecurityProperties.getWhiteList();
        if (whiteList == null) {
            whiteList = new ArrayList<>();
        }
        whiteList.addAll(Arrays.asList("/rsa/jwks.json", "/oauth/login"));
        return whiteList.toArray(new String[]{});
    }

    /**
     * 得到黑名单
     *
     * @return {@link String[]}
     */
    public String[] getBlackList() {
        List<String> whiteList = webSecurityProperties.getBlackList();
        if (whiteList == null) {
            return null;
        }
        return whiteList.toArray(new String[]{});
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
                .formLogin()
                //  禁用默认的表单登录
                // .disable()
                .and()
                // 授权请求
                .authorizeRequests()
                // 白名单,不需要认证
                .antMatchers(getWhiteList())
                .permitAll()
                // 黑名单,不准通过
                .antMatchers(getBlackList()).denyAll()
                // 任何请求，必须验证
                .anyRequest().authenticated()
                .and()
//             .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//             .and()
                .csrf().disable().cors();
        return http.build();
    }

    /**
     * 网络安全编辑器
     *
     * @param webSecurity 网络安全
     * @return {@link WebSecurityCustomizer}
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer(WebSecurity webSecurity) {
        return web -> web.ignoring().antMatchers("/resources/**");
    }

    /**
     * 全局配置
     *
     * @param auth 身份验证
     * @throws Exception 异常
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 密码编码器
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
